<template>
  <div class="bind-phone">
      <div class="input-section">
          <div class="cell phone-cell">
              <span class="cell-name">手机号</span>
              <input @textInput="textInutCheck('0',$event)" class="phone-text" type="number" ref="phoneText" @focus="phoneTextFocusHandle" @blur="phoneTextBlurHandle" v-model="phoneTextValue" placeholder="请输入手机号" >
              <div v-show="showClear" ref="clearBtn" @click="clearTextHandle" class="text-clear-div"><span class="iconfont icon-close"></span></div>
          </div>
          <div class="cell code-cell">
              <span class="cell-name">验证码</span>
              <input @textInput="textInutCheck('1',$event)" class="code-text" type="number" ref="codeText" v-model="codeTextValue" placeholder="请输入验证码" >
              <mt-button size="small" class="code-btn" type="default" @click.native="getCodeHandle">{{codeBtnWord}}</mt-button>
          </div>
      </div>
      <mt-button size="large" class="login-btn" type="default" @click.native="loginHandle">绑定</mt-button>
  </div>
</template>

<script>
import md5 from "js-md5";
import { mapState } from "vuex";
import Vue from "vue";
import { Toast, Button } from "mint-ui";
import "mint-ui/lib/button/style.css";
import "mint-ui/lib/toast/style.css";
Vue.component(Button.name, Button);
Vue.component(Toast.name, Toast);
import { savaToLocal, loadFromlLocal } from "../../../common/js/storage.js"; // 公共方法：本地缓存

export default {
  name: "bind-phone",
  data() {
    return {
      phoneTextValue: "",
      codeTextValue: "",
      codeBtnWord: "获取验证码",
      showClear: false,
      intervalId: -1000,
      leftSeconds: 0,
      codeBtn: null,
      canRequest: true,
      smsid: ""
    };
  },
  components: {},
  activated() {
    this.$store.dispatch("toggleLoading", false);
    this.codeTextValue = "";
  },
  mounted() {},
  beforeRouteLeave(to, from, next) {
    next();
  },
  watch: {
    phoneTextValue(val) {
      if (!val) this.showClear = false;
    }
  },
  methods: {
    textInutCheck(type, event) {
      if (!/^[0-9]*$/.test(event.data)) {
        event.returnValue = false;
      }
      if (type == "0") {
        if (this.phoneTextValue.length >= 11) event.returnValue = false;
        else this.showClear = true;
      } else {
        if (this.codeTextValue.length >= 4) event.returnValue = false;
      }
    },
    phoneTextFocusHandle() {
      if (this.phoneTextValue) this.showClear = true;
    },
    phoneTextBlurHandle() {
      this.showClear = false;
    },
    clearTextHandle(event) {
      this.phoneTextValue = "";
      this.$refs.phoneText.focus();
    },
    checkPhoneNum() {
      if (!this.phoneTextValue) {
        Toast({
          message: "请输入手机号码",
          iconClass: "iconfont icon-tishi1",
          duration: 1500
        });
        return false;
      } else {
        if (this.phoneTextValue.length < 11) {
          Toast({
            message: "请输入有效的手机号码",
            iconClass: "iconfont icon-tishi1",
            duration: 1500
          });
          return false;
        } else {
          var phnum = this.phoneTextValue.slice(0, 11);
          if (!/^1[34578]\d{9}$/.test(phnum)) {
            Toast({
              message: "请输入有效的手机号码",
              iconClass: "iconfont icon-tishi1",
              duration: 1500
            });
            return false;
          }
        }
      }
      return true;
    },
    checkCodeNum() {
      if (!this.codeTextValue) {
        Toast({
          message: "请输入验证码",
          iconClass: "iconfont icon-tishi1",
          duration: 1500
        });
        return false;
      } else if (this.codeTextValue.length != 4) {
        Toast({
          message: "验证码输入有误",
          iconClass: "iconfont icon-tishi1",
          duration: 1500
        });
        return false;
      }
      return true;
    },
    countSeconds: function() {
      this.leftSeconds = 60;
      this.codeBtnWord = "剩余" + this.leftSeconds + "s";
      if (!this.codeBtn)
        this.codeBtn = document.querySelector(".code-cell .code-btn");
      this.codeBtn.classList.add("count");
      this.intervalId = window.setInterval(() => {
        this.leftSeconds--;
        this.codeBtnWord = "剩余" + this.leftSeconds + "s";
        if (this.leftSeconds > 0) return;
        this.clearCodeInterval();
      }, 1000);
    },
    clearCodeInterval() {
      if (this.intervalId == -1000) return;
      window.clearInterval(this.intervalId);
      this.codeBtn.classList.remove("count");
      this.codeBtnWord = "获取验证码";
      this.intervalId = -1000;
    },
    getCodeHandle() {
      if (!this.canRequest) return;
      if (!this.checkPhoneNum()) return;
      this.canRequest = false;
      this.$http
        .post(this.path + "store/Sms/smssend", {
          uid: this.userid,
          mobile: this.phoneTextValue
        })
        .then(response => {
          this.canRequest = true;
          var respdata = response.body;
          if (respdata.status == "ok") {
            this.smsid = respdata.result;
            this.countSeconds();
          } else {
            Toast({
              message: respdata.msg,
              iconClass: "iconfont icon-tishi1",
              duration: 1500
            });
          }
        })
        .catch(response => {
          //请求出错处理
          console.log(response);
        });
    },
    loginHandle() {
      if (!this.canRequest) return;
      if (!this.checkPhoneNum()) return;
      if (!this.checkCodeNum()) return;
      this.canRequest = false;
      this.$http
        .post(this.path + "store/Sms/checkBindPhone", {
          smsid: this.smsid,
          uid: this.userid,
          code: this.codeTextValue
        })
        .then(response => {
          this.canRequest = true;
          var respdata = response.body;
          if (respdata.status == "ok") {
            Toast({
              message: "绑定成功!",
              iconClass: "iconfont icon-tishi1",
              duration: 1500
            });
            this.$store.commit("UPDATE_PHONENO", this.phoneTextValue);
            if (this.giftList && this.giftList.length > 0) {
              this.$store.commit("UPDATA_SHOW_GIFT_POPUP", true);
            }
            this.jumpToFromPage();
          } else {
            Toast({
              message: "绑定失败!",
              iconClass: "iconfont icon-tishi1",
              duration: 1500
            });
          }
        })
        .catch(response => {
          //请求出错处理
          console.log(response);
        });
    },
    jumpToFromPage() {
      // let redirect = decodeURIComponent(this.$route.query.redirect || '/');
      // this.$router.replace({path: redirect})
      this.$router.go(-1);
    }
  },
  computed: {
    ...mapState(["openid", "path", "userid", "giftList"])
  }
};
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
.bind-phone {
  font-family: 'Microsoft YaHei';
  display: flex;
  flex-direction: column;

  .input-section {
    margin-top: 0.24rem;
    padding: 0 0.2rem;
    box-sizing: border-box;

    .cell {
      margin-top: 0.12rem;
      width: 100%;
      height: 0.38rem;
      border-bottom: 1px #ddd solid;
      display: flex;
      align-items: center;
      position: relative;

      .cell-name {
        flex-shrink: 0;
        font-size: 0.12rem;
        color: #000;
        letter-spacing: 0.01rem;
      }

      input {
        flex: 1;
        width: 100%;
        -webkit-appearance: none; // 去掉iphone背景阴影
        border: none;
        outline: none;
        box-sizing: border-box;
        -webkit-touch-callout: none;
        color: #333;
        padding-left: 0.28rem;
        font-size: 0.14rem;
        position: relative;
        top: -0.01rem;
        letter-spacing: 0.005rem;

        &::-webkit-input-placeholder {
          color: #ddd;
          font-size: 0.12rem;
          letter-spacing: 0.01rem;
        }
      }

      .text-clear-div {
        position: absolute;
        right: 0px;
        top: 50%;
        transform: translate(-50%, -50%);

        span {
          font-size: 0.16rem;
          color: #8a8a8a;
        }
      }
    }

    .code-cell {
      .code-btn {
        flex: 0 0 0.88rem;
        background-color: #d9d9d9;
        color: #222;
        font-size: 0.12rem;
        height: 0.28rem;
        box-shadow: none;
        border-radius: 0;
        letter-spacing: 0.005rem;

        &.count {
          font-size: 0.12rem;
          pointer-events: none;
          color: #666;
          background-color: #e3e3e3;
        }
      }
    }
  }

  .login-btn {
    background-color: #b37287;
    color: #fff;
    margin-top: 0.5rem;
    margin-left: 0.25rem;
    width: calc(100% - 0.5rem);
    font-size: 0.12rem;
    letter-spacing: 0.02rem;
    height: 0.32rem;
    box-shadow: none;
  }
}
</style>
